package com.example.yan_music.widge;
/**
 * <p>
 *      自定义下拉窗帘View
 *      暂未完善，要求功能是把搜索历史记录放入窗帘中
 * </p>
 */

import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.BounceInterpolator;
import android.view.animation.Interpolator;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Scroller;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.yan_music.R;
import com.example.yan_music.adapter.RcvHistoryAdapter;
import com.example.yan_music.db.table.HistoryRecord;
import com.example.yan_music.presenter.ISearchPresenterImp;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

public class CurtainView extends RelativeLayout implements View.OnTouchListener {
    private static String TAG = "CurtainView";
    private Context mContext;
    /**
     * Scroller 拖动类
     */
    private Scroller mScroller;
    /**
     * 屏幕高度
     */
    private int mScreenHeight = 0;
    /**
     * 屏幕宽度
     */
    private int mScreenWidth = 0;
    /**
     * 点击时候Y的坐标
     */
    private int downY = 0;
    /**
     * 拖动时候Y的坐标
     */
    private int moveY = 0;
    /**
     * 拖动时候Y的方向距离
     */
    private int scrollY = 0;
    /**
     * 松开时候Y的坐标
     */
    private int upY = 0;
    /**
     * 广告幕布的高度
     */
    private int recyclerViewHeight = 0;
    /**
     * 是否 打开
     */
    private boolean isOpen = false;
    /**
     * 是否在动画
     */
    private boolean isMove = false;
    /**
     * 绳子的图片
     */
    private ImageView img_curtain_rope;
    /** 广告的图片*/
    //private ImageView img_curtain_ad;
    /**
     * RecyclerView
     */
    private RecyclerView mRecyclerView;
    /**
     * 上升动画时间
     */
    private int upDuration = 1000;
    /**
     * 下落动画时间
     */
    private int downDuration = 500;

    private ArrayList<HistoryRecord> mHistoryList = new ArrayList<>();
    private RcvHistoryAdapter mHistoryAdapter;
    private String mSearchRecord;
    private ISearchPresenterImp iSearchPresenterImp;

    public CurtainView(Context context) {
        super(context);
        init(context);
    }

    public CurtainView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    public CurtainView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }



    /**
     * 初始化
     */
    private void init(Context context) {
        this.mContext = context;
        iSearchPresenterImp = new ISearchPresenterImp();
        mHistoryList.addAll(LitePal.findAll(HistoryRecord.class));
        mHistoryAdapter = new RcvHistoryAdapter(context, mHistoryList, iSearchPresenterImp);
        mRecyclerView.setLayoutManager(new GridLayoutManager(context, 6));
        mRecyclerView.setAdapter(mHistoryAdapter);

        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels; // 屏幕宽度（像素）
        int height = dm.heightPixels; // 屏幕高度（像素）
        float density = dm.density; // 屏幕的密度，用来计算dp
        int screenWidth = (int) (width / density); // 屏幕的宽度（dp）
        int screenHeight = (int) (height / density); // 屏幕的高度（dp）

        //Interpolator 设置为有反弹效果的  （Bounce：反弹）
        Interpolator interpolator = new BounceInterpolator();
        mScroller = new Scroller(context, interpolator);

        mScreenHeight = screenHeight;
        mScreenWidth = screenWidth;

        // 背景设置成透明
        this.setBackgroundColor(Color.argb(0, 0, 0, 0));
        final View view = LayoutInflater.from(mContext).inflate(R.layout.layout_curtain, null);
        //img_curtain_ad = (ImageView) view.findViewById(R.id.cus_img_1);
        mRecyclerView = view.findViewById(R.id.rcv_hist);
        img_curtain_rope = (ImageView) view.findViewById(R.id.cus_img_2);
        addView(view);

        mRecyclerView.post(new Runnable() {

            @Override
            public void run() {
                recyclerViewHeight = mRecyclerView.getHeight();
                //在当前视图内容偏移至(x , y)坐标处.
                CurtainView.this.scrollTo(0, recyclerViewHeight);
                Log.i(TAG, "窗帘高度 recyclerViewHeight=" + recyclerViewHeight);
            }
        });
        img_curtain_rope.setOnTouchListener(this);
    }

    /**
     * 拖动动画
     *
     * @param startY
     * @param dy       垂直距离, 滚动的y距离
     * @param duration 时间
     */
    public void startMoveAnim(int startY, int dy, int duration) {
        isMove = true;
        mScroller.startScroll(0, startY, 0, dy, duration);
        invalidate();//通知UI线程的更新
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
    }

    @Override
    public void computeScroll() {
        //判断是否还在滚动，还在滚动为true
        if (mScroller.computeScrollOffset()) {
            scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
            //更新界面
            postInvalidate();
            isMove = true;
        } else {
            isMove = false;
        }
        super.computeScroll();
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (!isMove) {
            int offViewY = 0;//屏幕顶部和该布局顶部的距离
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    downY = (int) event.getRawY();
                    offViewY = downY - (int) event.getX();
                    Log.d(TAG, "onTouch: " + "点击时的Y坐标downY=" + downY + "; 屏幕顶部与该布局的高度差offViewY=" + offViewY);
                    return true;
                case MotionEvent.ACTION_MOVE:
                    moveY = (int) event.getRawY();
                    Log.d(TAG, "onTouch: 拖动时Y的坐标为moveY=" + moveY);
                    scrollY = moveY - downY;
                    Log.d(TAG, "onTouch: 拖动时Y的方向距离scrollY=" + scrollY);
                    if (scrollY < 0) {
                        // 向上滑动
                        if (isOpen) {
                            if (Math.abs(scrollY) <= mRecyclerView.getBottom() - offViewY) {
                                scrollTo(0, -scrollY);
                            }
                        }
                    } else {
                        // 向下滑动
                        if (!isOpen) {
                            if (scrollY <= recyclerViewHeight) {
                                scrollTo(0, recyclerViewHeight - scrollY);
                            }
                        }
                    }
                    break;
                case MotionEvent.ACTION_UP:
                    upY = (int) event.getRawY();
                    if (Math.abs(upY - downY) < 10) {
                        onRopeClick();
                        break;
                    }
                    if (downY > upY) {
                        // 向上滑动
                        if (isOpen) {
                            if (Math.abs(scrollY) > recyclerViewHeight / 2) {
                                // 向上滑动超过半个屏幕高的时候 开启向上消失动画
                                startMoveAnim(this.getScrollY(),
                                        (recyclerViewHeight - this.getScrollY()), upDuration);
                                isOpen = false;
                            } else {
                                startMoveAnim(this.getScrollY(), -this.getScrollY(), upDuration);
                                isOpen = true;
                            }
                        }
                    } else {
                        // 向下滑动
                        if (scrollY > recyclerViewHeight / 2) {
                            // 向上滑动超过半个屏幕高的时候 开启向上消失动画
                            startMoveAnim(this.getScrollY(), -this.getScrollY(), upDuration);
                            isOpen = true;
                        } else {
                            startMoveAnim(this.getScrollY(), (recyclerViewHeight - this.getScrollY()), upDuration);
                            isOpen = false;
                        }
                    }
                    break;
                default:
                    break;
            }
        }
        return false;
    }

    /**
     * 点击绳索开关，会展开关闭
     * 在onTouch中使用这个中的方法来当点击事件，避免了点击时候响应onTouch的衔接不完美的影响
     */
    public void onRopeClick() {
        if (isOpen) {
            CurtainView.this.startMoveAnim(0, recyclerViewHeight, upDuration);
        } else {
            CurtainView.this.startMoveAnim(recyclerViewHeight, -recyclerViewHeight, downDuration);
        }
        isOpen = !isOpen;
    }
}
